
var EpyGroups = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    panel: null,
    content: null,
    listData: null,
    maindropzone: null,
    zones: [],
    curPage:0,
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        this.createTable();
    },
    createTable: function() {

        this.content = new Element('div#content');
        this.listData = new Element('table#listData[rules=groups]');
        this.maindropzone = new Element('div.dropzone[html=&nbsp;]').store('gid', 0);
        this.zones.include(this.maindropzone);

        this.panel.adopt(
            this.maindropzone,
            new Element('div.tl', { html: '<div class="tr"><div>&nbsp;</div></div>' }),
            this.content.adopt(this.listData),
            new Element('div.bl', { html: '<div class="br"><div>&nbsp;</div></div>]' })
        );

        this.listData.adopt(
            new Element('thead', { html:
                '<tr><th class="imgCol">&nbsp;</th><th class="brdCol w150">Group name</th>' +
                '<th class="brdCol center w50">amazon<br/>defQty-subQty-margin-charge</th>' +
                '<th class="brdCol center w50">amazoncomp<br/>defQty-subQty-margin-charge</th>' +
                '<th class="brdCol center w50">ebay<br/>defQty-subQty-margin-charge</th>' +
                '<th class="brdCol center w50">ebaya<br/>defQty-subQty-margin-charge</th>' +
                '<th class="brdCol center w50">buycom<br/>defQty-subQty-margin-charge</th></tr>'
            }),
            new Element('tfoot', { html: '<tr><th class="tdFull" colspan=8>&nbsp;</tr>' }),
            new Element('tbody')
        );

        //
        this.epyRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Loading...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.fillContent(data);
            }.bind(this)
        }).send('table=epy&ex=groups&nc=' + Date.now());

    },
    fillContent: function(data) {

        this.maindropzone.empty();
        var drag;
        data.cats.each(function(cat) {
            drag = new Element('div.draggable').adopt(
                new Element('b[html=&nbsp;&nbsp;&nbsp;&nbsp;]'),
                new Element('a[text=' + cat.name + '][href=javascript:;]', {
                    'events': {
                        'focus': function() {this.blur();}
                    }
                })
            ).store('cid',cat.id).store('gid', 0);
            this.maindropzone.adopt(drag);
        }, this);

        var group,tbody,tr,tdo,color = false,tagid;
        tbody = this.listData.getElement('tbody');
        tbody.empty();

        data.groups.sort(this.sortName).each(function(group, idx) {

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'epy_' + idx;
            tdo = new Element('td.imgCol]').adopt(
                new Element('a.plus[href=javascript:;][html=&nbsp;][title=Open Category]',{
                    'events': {
                        'click': this.doCategory.bind(this, group.id, tagid),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                tr.adopt(
                    tdo,
                    new Element('td.brdCol.left.w150[text=' + group.name +']'),
                    new Element('td.brdCol.w50').adopt(this.addTable(group.amazon, group.id, 'amazon')),
                    new Element('td.brdCol.w50').adopt(this.addTable(group.amzcomp, group.id, 'amzcomp')),
                    new Element('td.brdCol.w50').adopt(this.addTable(group.ebay, group.id, 'ebay')),
                    new Element('td.brdCol.w50').adopt(this.addTable(group.ebayali, group.id, 'ebayali')),
                    new Element('td.brdCol.w50').adopt(this.addTable(group.buycom, group.id, 'buycom'))
                )
            );

            var dropzone = new Element('div.dropzone[html=&nbsp;]').store('gid', group.id);
            this.zones.include(dropzone);

            tbody.adopt(
                new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=8][style=padding-top:0]').adopt(
                        new Element('div.green[text=group global category:]'),
                        dropzone,
                        new Element('div') // for items table
                    )
                )
            );

        }, this);// for

        this.makeDragable(this.maindropzone);
    },
    addTable: function(adv, id, name) {
        return new Element('table#adtable.addef', {
            'events': {
                'click': this.editGroup.bind(this, id, name),
                'mouseenter': function() {this.removeClass('addef').addClass('adenter');},
                'mouseleave': function() {this.removeClass('adenter').addClass('addef');},
                'focus': function() {this.blur();}
            },
            'html' :
            '<tr><th>0 - 30:</th><td>'    + adv.defQty0_30     + '</td><td>' + adv.minQty0_30     + '</td><td>' + adv.margin0_30     + '%</td><td>$' + numberFormat(adv.charge0_30) + '</td></tr>' +
            '<tr><th>31 - 60:</th><td>'   + adv.defQty31_60    + '</td><td>' + adv.minQty31_60    + '</td><td>' + adv.margin31_60    + '%</td><td>$' + numberFormat(adv.charge31_60)+ '</td></tr>' +
            '<tr><th>61 - 90:</th><td>'   + adv.defQty61_90    + '</td><td>' + adv.minQty61_90    + '</td><td>' + adv.margin61_90    + '%</td><td>$' + numberFormat(adv.charge61_90) + '</td></tr>' +
            '<tr><th>91 - 180:</th><td>'  + adv.defQty91_180   + '</td><td>' + adv.minQty91_180   + '</td><td>' + adv.margin91_180   + '%</td><td>$' + numberFormat(adv.charge91_180) + '</td></tr>' +
            '<tr><th>181 - 240:</th><td>' + adv.defQty181_240  + '</td><td>' + adv.minQty181_240  + '</td><td>' + adv.margin181_240  + '%</td><td>$' + numberFormat(adv.charge181_240) + '</td></tr>' +
            '<tr><th>240+:</th><td>'      + adv.defQty241_more + '</td><td>' + adv.minQty241_more + '</td><td>' + adv.margin241_more + '%</td><td>$' + numberFormat(adv.charge241_more) + '</td></tr>'
        });
    },
    doCategory: function(groupid, tagid, ev) {

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus');

            //
            this.epysubcatRequest = new Request({
                url: '/Admin/webstat/getFromMySQL',
                method: 'get',
                onRequest: function() {
                    new ShowBox().say('Open...');
                    new Loader().show();
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('[' + resp + ']');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    new Loader().hide();

                    this.fillGroupZone(data, groupid, dcuc);
                }.bind(this)
            }).send('table=epy&ex=getGroupSubcat&gid=' + groupid + '&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            ev.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }
    },
    fillGroupZone: function(data, groupid, tag) {

        var groupzone = tag.getElement('div.dropzone');
        groupzone.empty().set('html','&nbsp;');

        var drag;
        data.each(function(cat) {
            drag = new Element('div.draggable').adopt(
                new Element('b[html=&nbsp;&nbsp;&nbsp;&nbsp;]'),
                new Element('a[href=javascript:;][text=' + cat.name + ']',{
                    'events': {
                        'click': this.openItems.bind(this, cat.id),
                        'focus': function() {this.blur();}
                    }
                })
            ).store('cid',cat.id).store('gid', groupid);
            groupzone.adopt(drag);
        }, this);

        this.makeDragable(groupzone);
    },
    makeDragable: function(dropzone) {
        var dragElements = dropzone.getElements('div.draggable');
        dragElements.each(function(elm) {
            elm.makeDraggable({
                droppables: this.zones,
                handle: elm.getElement('b'),
                onSnap: function(el) {
                    el.setStyles({'opacity': 0.5, 'z-index': 1});
                },
                onComplete: function(el) {
                    el.setStyles({'opacity': 1.0, 'z-index': 0, 'left':0, 'top':0 });
                },
                onDrop: function(el, dropzone, ev) {
                    if(dropzone) {
                        dropzone.adopt(el).removeClass("dragenter");

                        if(dropzone.retrieve('gid') != el.retrieve('gid')) {
                            el.getElement('a').removeEvents('click');
                            if(dropzone.retrieve('gid') != 0) {
                                el.getElement('a').addEvent('click', this.openItems.bind(this, el.retrieve('cid')));
                            }
                            //
                            this.epyDragRequest = new Request({
                                url: '/Admin/webstat/getFromMySQL',
                                method: 'post',
                                onRequest: function() {
                                    new ShowBox().say('Store you drag...');
                                    new Loader().show();
                                },
                                onComplete: function() {
                                    new Loader().hide();
                                }
                            }).send('table=epy&ex=drag&nc=' + Date.now() + '&nzone=' + dropzone.retrieve('gid') + '&ozone=' + el.retrieve('gid') + '&cid=' + el.retrieve('cid'));

                            el.store('gid', dropzone.retrieve('gid'));
                        }
                    }
                }.bind(this),
                onEnter: function(el, droppable) {
                    droppable.addClass("dragenter");
                },
                onLeave: function(el, droppable) {
                    droppable.removeClass("dragenter");
                }
            });
        }, this);
    },
    openItems: function(catid, ev) {
        ev.stop();

        var div = ev.target.getParent('div.dropzone').getNext('div');

        var pager = new Element('td.right');
        var ptab = new Element('table#pager').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('td.left[html=&nbsp;]'),
                    pager
                )
            )
        );

        this.pager = new Pager({
            'tagid': pager,
            onNewpage: function(currentPage) {
                this.curPage = currentPage;

                this.openItemsRequest.send('table=epy&ex=getItems&cid=' + catid + '&curPage=' + this.curPage + '&nc=' + Date.now());
            }.bind(this)
        });


        var cont = new Element('div#content');
        this.itemData = new Element('table#listData[rules=groups]');
        div.empty().adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            cont.adopt(ptab, this.itemData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        );


        // make head
        this.itemData.adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.brdCol.w50[text=SKU]'),
                    new Element('th.brdCol.w15[text=Vendor]'),
                    new Element('th.brdCol.w80[text=Name]'),
                    new Element('th.brdCol.w50[text=Hot Price]'),
                    new Element('th.brdCol.w50[text=Sell Price]'),
                    new Element('th.brdCol.w15[text=Stock]'),
                    new Element('th.brdCol.w15[text=Qty]')
                )
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[html=&nbsp;][colspan=7]')
                )
            ),
            new Element('tbody')
        );

        //
        this.openItemsRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Opening...');
                new Loader().show();
            },
            onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('(' + resp + ')');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    new Loader().hide();

                this.showItems(data);
            }.bind(this)
        }).send('table=epy&ex=getItems&cid=' + catid + '&nc=' + Date.now());

    },
    showItems: function(items) {
        this.pager.setData(this.curPage, items.cntPage, items.onPage, items.rows.length);

        var tbody = this.itemData.getElement('tbody'),item,tr,color=false;
        tbody.empty();

        for(var i = 0; i < items.rows.length; i++) {
            item = items.rows[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tbody.adopt(
                tr.adopt(
                    new Element('td.imgCol.w50[text=' + item.sku + ']'),
                    new Element('td.brdCol.center.w15[html=<em title="' + item.vndname + '">' + item.als + '</em>]'),
                    new Element('td.brdCol.left.w80[text=' + item.iname + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(item.hotPrice) + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(item.sellPrice) + ']'),
                    new Element('td.brdCol.center.w15[text=' + (item.stock ? 'Y': 'N')  + ']'),
                    new Element('td.brdCol.center.w15[text=' + (item.qty ? item.qty: '')  + ']')
                )
            );
        }

    },
    editGroup: function(groupid, name, ev) {
        ev.stop();
        new EditGroup({
            'groupid':  groupid,
            'advname':  name,
            'targetid': ev.target,
            onReload: function() {
                this.epyRequest.send('table=epy&ex=groups&nc=' + Date.now());
            }.bind(this)
        });
    },
    sortName: function(a, b) {
	return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
    }
});


var EditGroup = new Class({
    Implements: [Events, Options],
    options: {
        groupid: 0,
        advname:  '',
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);
        if(!this.options.groupid) return;

        this.groupchange = new Request({
            'url': '/Admin/webstat/getFromMySQL',
            'method': 'post',
            'onRequest': function() {
                new ShowBox().say('Edit...');
                new Loader().show();
            },
            'onComplete': function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.makeForm(data);
            }.bind(this)
        }).send('table=epy&ex=getEpyGroup&gid=' + this.options.groupid + '&adv=' + this.options.advname + '&nc=' + Date.now());

    },
    makeForm: function(group) {

        this.update = new Element('a.update.closeThis[href=javascript:;][html=&nbsp;][title=Update Group]');
        this.create = new Element('a.create.closeThis[href=javascript:;][html=&nbsp;][title=Create New Group]');
        this.erase = new Element('a.erase.closeThis[href=javascript:;][html=&nbsp;][title=Erase Group]');

        //make body
        var prefname = (this.options.advname ? this.options.advname + '_' : '' );
        this.table = new Element('table#ggroup').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('th.col[colspan=3]',{'html':'Group Name : <input style="text-align:left;width:230px;" name="name" type="text" maxlength=50 value="' + group.name + '"/>'}),
                    new Element('th.col[colspan=2]',{'html':'Active : <input name="active" type="checkbox" ' + (group.active ? 'checked="checked"': '' ) + ' />'})
                ),
                new Element('tr').adopt(new Element('td.sep[html=<hr/>][colspan=5]')),
                new Element('tr').adopt(
                    new Element('th.col[text=Older(days)]'),
                    new Element('th.col[text=DefQty(stock=Y)]'),
                    new Element('th.col[text=SubQty -]'),
                    new Element('th.col[text=Margin %]'),
                    new Element('th.col[text=SubCharge $]')
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=0 - 30]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty0_30" maxlength=6 value="' + (group.defQty0_30 ? group.defQty0_30: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty0_30" maxlength=6 value="' + (group.minQty0_30 ? group.minQty0_30: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin0_30" maxlength=6 value="' + (group.margin0_30 ? group.margin0_30: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge0_30" maxlength=6 value="' + (group.charge0_30 ? group.charge0_30: '') + '"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=31 - 60]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty31_60" maxlength=6 value="' + (group.defQty31_60 ? group.defQty31_60: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty31_60" maxlength=6 value="' + (group.minQty31_60 ? group.minQty31_60: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin31_60" maxlength=6 value="' + (group.margin31_60 ? group.margin31_60: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge31_60" maxlength=6 value="' + (group.charge31_60 ? group.charge31_60: '') + '"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=61 - 90]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty61_90" maxlength=6 value="' + (group.defQty61_90 ? group.defQty61_90: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty61_90" maxlength=6 value="' + (group.minQty61_90 ? group.minQty61_90: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin61_90" maxlength=6 value="' + (group.margin61_90 ? group.margin61_90: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge61_90" maxlength=6 value="' + (group.charge61_90 ? group.charge61_90: '') + '"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=91 - 180]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty91_180" maxlength=6 value="' + (group.defQty91_180 ? group.defQty91_180: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty91_180" maxlength=6 value="' + (group.minQty91_180 ? group.minQty91_180: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin91_180" maxlength=6 value="' + (group.margin91_180 ? group.margin91_180: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge91_180" maxlength=6 value="' + (group.charge91_180 ? group.charge91_180: '') + '"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=181 - 240]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty181_240" maxlength=6 value="' + (group.defQty181_240 ? group.defQty181_240: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty181_240" maxlength=6 value="' + (group.minQty181_240 ? group.minQty181_240: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin181_240" maxlength=6 value="' + (group.margin181_240 ? group.margin181_240: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge181_240" maxlength=6 value="' + (group.charge181_240 ? group.charge181_240: '') + '"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[text=241 - more]'),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'defQty241_more" maxlength=6 value="' + (group.defQty241_more ? group.defQty241_more: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'minQty241_more" maxlength=6 value="' + (group.minQty241_more ? group.minQty241_more: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'margin241_more" maxlength=6 value="' + (group.margin241_more ? group.margin241_more: '') + '"/>'}),
                    new Element('td.col',{'html':'<input type="text" name="' + prefname + 'charge241_more" maxlength=6 value="' + (group.charge241_more ? group.charge241_more: '') + '"/>'})
                ),
                new Element('tr').adopt(new Element('td.sep[html=<hr/>][colspan=5]')),
                new Element('tr').adopt(
                    new Element('td.col').adopt(
                        this.update,
                        new Element('em[text=Update]')
                    ),
                    new Element('td.col[colspan=2]').adopt(
                        this.create,
                        new Element('em[text=Create]')
                    ),
                    new Element('td.col[colspan=4]').adopt(
                        this.erase,
                        new Element('em[text=Erase]')
                    )
                )
            )
        );

        new ModalBox({
            width: 610,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.update.addEvents({'click': this.updateGroup.bind(this, group.id), 'focus': function() {this.blur();} });
                this.create.addEvents({'click': this.createGroup.bind(this), 'focus': function() {this.blur();} });
                this.erase.addEvents({'click': this.eraseGroup.bind(this, group.id), 'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Group: ' + group.name + '</h2>', new Element('center').adopt(this.table));

    },
    updateGroup: function(groupid) {

        var inpts = this.table.getElements('input'),parms = '&cb=';
        inpts.each(function(inp, idx) {
            parms += (idx++ > 0 ? ',' : '') + inp.get('name') + '=\'' + (inp.get('type') == 'text' ? (inp.get('value') ? inp.get('value'): 0): (inp.get('checked') ? 1: 0)) +'\'';
        });

        //this.groupchange.send('table=epy&ex=upEpyGroup&gid=' + groupid + '&nc=' + Date.now() + parms);
        new Request({
            'url': '/Admin/webstat/getFromMySQL',
            'method': 'post',
            'onRequest': function() {
                new ShowBox().say('update...');
                new Loader().show();
            },
            'onComplete': function() {
                new Loader().hide();
            }
        }).send('table=epy&ex=upEpyGroup&gid=' + groupid + '&nc=' + Date.now() + parms);

        this.fireEvent('reload');
    },
    createGroup: function() {

        var inpts = this.table.getElements('input'),parms = '&cb=';
        inpts.each(function(inp, idx) {
            parms += (idx++ > 0 ? ',' : '') + inp.get('name') + '=\'' + (inp.get('type') == 'text' ? (inp.get('value') ? inp.get('value'): 0): (inp.get('checked') ? 1: 0)) +'\'';
        });

        this.groupchange.send('table=epy&ex=crEpyGroup&nc=' + Date.now() + parms);

        this.fireEvent('reload');
    },
    eraseGroup: function(groupid) {

        this.groupchange.send('table=epy&ex=erEpyGroup&gid=' + groupid + '&nc=' + Date.now());

        this.fireEvent('reload');
    }
});

